package com.aaa.hospital.controller;

import com.aaa.hospital.pojo.domain.Post;
import com.aaa.hospital.pojo.query.PostQuery;
import com.aaa.hospital.pojo.vo.PostVO;
import com.aaa.hospital.result.AjaxResult;
import com.aaa.hospital.service.PostService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;



import java.io.InputStream;
import java.io.UnsupportedEncodingException;


import java.io.InputStream;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @Author: danghui
 * @Date: 2022/2/21 16:02
 * @Description: TODO
 */
@Controller
@RequestMapping("PostSource")
public class PostSourceController {
    @Autowired
    private PostService postService;

    @RequestMapping("download")
    public void download(PostQuery postQuery, HttpServletResponse response) throws Exception {
        AjaxResult ajaxResult = postService.queryPost(postQuery);
        Map data = (Map) ajaxResult.getData();
        List<Post> currentData = (List<Post>) data.get("currentData");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        String fileName = URLEncoder.encode("职位信息", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        EasyExcel.write(   response.getOutputStream()  , Post.class    )     .sheet("职位信息").doWrite( currentData);

    }
    @RequestMapping("upload")
    public AjaxResult upload(MultipartFile haha)throws Exception{
        byte[] bytes = haha.getBytes();
        String name = haha.getName();
        long size = haha.getSize();
        String originalFilename = haha.getOriginalFilename();
        String contentType = haha.getContentType();
        InputStream inputStream = haha.getInputStream();

        ExcelReaderBuilder read = EasyExcel.read(haha.getInputStream(), PostVO.class,null);
        List<PostVO> objects = read.doReadAllSync();
        Integer a = 0;
        for (PostVO object : objects) {
            AjaxResult ajaxResult = postService.addPost(object);
            if (ajaxResult.getCode()==1){
                a++;
            }
        }
        if(a>0){
            return AjaxResult.success();
        }else {
            return AjaxResult.fail();
        }
    }
}
